package com.lzq.rabbitmqdemo.java_api.rpc;

import com.lzq.rabbitmqdemo.java_api.constant.ConnectionConfig;
import com.lzq.rabbitmqdemo.java_api.constant.Constants;
import com.rabbitmq.client.*;

import java.io.IOException;

public class RPCServer {
    public static void main(String[] args) throws Exception{
        //1.创建连接
        ConnectionFactory factory = ConnectionConfig.getFactory();
        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel()) {
            //2.声明队列
            channel.queueDeclare(Constants.RPC_REQUEST_QUEUE_NAME, true, false, false, null);
            //3.接收消息, 并消费
            //设置同时最多只能获取⼀个消息
            channel.basicQos(1);
            System.out.println("Awaiting RPC request");
            Consumer consumer = new DefaultConsumer(channel){
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope,
                                           AMQP.BasicProperties properties, byte[] body) throws IOException {
                    AMQP.BasicProperties replyProps = new AMQP.BasicProperties
                            .Builder()
                            .correlationId(properties.getCorrelationId())
                            .build();
                    // ⽣成返回
                    String message = new String(body);
                    String response = "request:"+ message + ", response: 处理成功 ";
                    //回复消息，通知已经收到请求
                    channel.basicPublish( "", properties.getReplyTo(), replyProps,
                            response.getBytes());
                    //对消息进⾏应答
                    channel.basicAck(envelope.getDeliveryTag(), false);
                }
            };
            channel.basicConsume(Constants.RPC_REQUEST_QUEUE_NAME, false,
                    consumer);
            Thread.sleep(10000);
        }
    }
}
